import { get } from "@ap/util/request";
import { showErrorMessage } from "@ap/util/vscode/message";
import * as vscode from "vscode";
import downloadNPMPackage from "./downloadNPMPackage";

let npmSearchItems: vscode.QuickPickItem[] | undefined;

async function getNPMPackage(name: string) {
  const requestOptions = {
    url: "https://registry.npmjs.com/-/v1/search?text=" + name,
  };
  /**
   * 发送请求并等待响应。
   */
  const response = await get<Record<string, any>>(requestOptions, "npm包数据");
  /**
   * 检查响应是否成功，如果不成功则返回错误消息。
   */
  if (!response) {
    showErrorMessage(`获取npm包数据失败`);
    return;
  }
  const filteredObjects = response.objects.map((item: any) => ({
    ...item,
    timestamp: new Date(item.package.date).getTime(),
  }));

  // 排序
  filteredObjects.sort((a: any, b: any) => {
    return b.timestamp - a.timestamp;
  });
  const dataSource: vscode.QuickPickItem[] = filteredObjects.map(
    (item: any) => ({
      label: `${item.package.name}`,
      description: `${item.package.publisher.username || "佚名"} | v${item.package.version.toString()}`,
      detail: `${item.package.description.toString()}`,
    }),
  );
  return dataSource;
}

export async function npmSearchShowBar() {
  try {
    if (!npmSearchItems) {
      npmSearchItems = await getNPMPackage("@dao3fun/");
    }
    if (!npmSearchItems) {
      return "获取失败";
    }
    const selectedOption = await vscode.window.showQuickPick(npmSearchItems, {
      title: "神岛NPM包列表",
      matchOnDescription: true,
      canPickMany: false,
    });

    if (selectedOption) {
      downloadNPMPackage(
        selectedOption.label,
        "https://www.npmjs.com/package/" + selectedOption.label,
      );
    }
    return npmSearchItems;
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
    return error;
  }
}
